package com.wangp.mywrite.s_netty.nio.ch3.nonblock_mode;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.*;
import java.nio.charset.StandardCharsets;
import java.util.Iterator;

/**
 * @description: TODO
 * @author tooStronger
 * @date 2023/3/16
 */
public class WriteServer {

    public static void main(String[] args) throws IOException {
        ServerSocketChannel ssc = ServerSocketChannel.open();
        ssc.configureBlocking(false);

        Selector selector = Selector.open();
        ssc.register(selector, SelectionKey.OP_ACCEPT);

        ssc.bind(new InetSocketAddress(8080));
        while (true) {
            selector.select();
            Iterator<SelectionKey> iterator = selector.selectedKeys().iterator();
            while (iterator.hasNext()) {
                SelectionKey key = iterator.next();
                iterator.remove();
                if (key.isAcceptable()) {
                    SocketChannel sc = ssc.accept();
                    sc.configureBlocking(false);
                    SelectionKey scKey = sc.register(selector, 0, null);
                    scKey.interestOps(SelectionKey.OP_READ);

                    // 向客服端发送大量数据
                    StringBuilder sb = new StringBuilder();
                    for (int i = 0; i < 5_0000_0000; i++) {
                        sb.append("a");
                    }
                    ByteBuffer buffer = StandardCharsets.UTF_8.encode(sb.toString());
                    // 2. 返回值为实际写入字节数
                    int write = sc.write(buffer);
                    System.out.println("write : " + write);
                    // 使用 while 可能导致 server 端不停发数据，我电脑没复现
//                    while (buffer.hasRemaining()) {
                    // 3. hasRemaining 判断是否有剩余内容
                    if (buffer.hasRemaining()) {
                        // 4.关注可写事件
                        scKey.interestOps(scKey.interestOps() | SelectionKey.OP_WRITE);
                        // 5.未写完数据挂到scKey上
                        scKey.attach(buffer);
                    }
                } else if (key.isWritable()) {
                    ByteBuffer buffer = (ByteBuffer) key.attachment();
                    SocketChannel sc = (SocketChannel) key.channel();
                    int write = sc.write(buffer);
                    System.out.println("write: " + write);
                    // 6.清理buffer
                    if (!buffer.hasRemaining()) {
                        // 清除 buffer
                        key.attach(null);
                        // 不再关注写事件
                        key.interestOps(key.interestOps() ^ SelectionKey.OP_WRITE & key.interestOps());
                    }
                }
            }
        }
    }
}
